const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fetch = require('node-fetch');
const SQLiteHelper = require("./database/sqlLiteUtil.cjs")
// console.log(22)
const chatClient = require('./mcp/index.cjs'); // 或 index.js，根据你的实际文件后缀
// const

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';

const sqlLite = new SQLiteHelper();

sqlLite.initDatabase()
// 结构化存储 electron-store
const Store = require('electron-store');
const store = new Store();


function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 1300,
        height: 800,
        autoHideMenuBar: true,
        minWidth: 1300,
        minHeight: 800,
        webPreferences: {
            preload: path.resolve(__dirname, './preload.js'),
            contextIsolation: true,
            enableRemoteModule: true,
        },
    });

    const env = 'pro';
    if (env === 'pro') {
        const elePath = path.join(__dirname, '../node_modules/electron');
        require('electron-reload')('../', {
            electron: require(elePath),
        });
        mainWindow.loadURL('http://localhost:8888');
        mainWindow.webContents.openDevTools();
    } else {
        mainWindow.loadFile(path.resolve(__dirname, '../dist/index.html'));
    }
}

app.whenReady().then(() => {
    createWindow();

    ipcMain.handle("call-maas", async (event, payload) => {

        const res = await fetch("https://maas-api.cn-huabei-1.xf-yun.com/v1/chat/completions", {
            method: "POST",
            headers: {
                Authorization: `Bearer sk-fUlXbvaD9R3shYo036971c2640914506B58057C5D7D23a71`,
                "Content-Type": "application/json",
            },
            body: payload,
        });

        const result = await res.json();
        return result;
    });


    ipcMain.handle("chat", async (event, question) => {
        console.log("收到的提问:" , question);
        return chatClient.processQuery(question);
    });

    ipcMain.handle("create-chat", async (event, intent) => {
        console.log(`create-chat:收到传参:${intent}`);
        return chatClient.processQuery(question);
    });


    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});
